package com.medialog.am.core;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.medialog.am.vo.CollectInfo;
import com.medialog.am.vo.ConnectionInfo;
import com.medialog.am.vo.cmd;




public class SshObject implements cmd {

	static Logger logger = Logger.getLogger(SshObject.class);
	
	public SshObject() {
	}

	public List<CollectInfo> getResourceList(List<ConnectionInfo> connectionInfoList) throws Exception {
		
		logger.debug("getReourceList entry");
		List<CollectInfo> collectInfoList = new ArrayList<CollectInfo>();
		
		for (ConnectionInfo connectionInfo : connectionInfoList) {
			
			for(int i =0; i<3; i++){
				Session session = null;
				try {
					
					logger.debug("Server Information [ID :"+ connectionInfo.getSvrId()+" HOST : "+connectionInfo.getHost()+" PORT : "+connectionInfo.getPortNum()+" PW : "+connectionInfo.getSvrPw()+"]");
					JSch jsch = new JSch();
					session = jsch.getSession(connectionInfo.getSvrId(),connectionInfo.getHost(),connectionInfo.getPortNum());
					session.setPassword(connectionInfo.getSvrPw());
					
					session.setConfig("StrictHostKeyChecking", "no");
					session.connect();
					
					logger.debug("StreamInout entry");		
					String usedCpu = StreamInOut(cpuCmd, session);
					String usedMem = StreamInOut(memCmd, session);
					String usedHdd = StreamInOut(hddCmd, session);
					String totalMem = StreamInOut(totalMemCmd, session);
					String totalHdd = StreamInOut(totalHddCmd, session);
					logger.debug("StreamInOut exit");
					CollectInfo collectInfo = new CollectInfo(connectionInfo.getSvrNum(),connectionInfo.getSerialNo(),usedCpu, usedMem, usedHdd, totalMem, totalHdd, connectionInfo.getCpuCritical(),
							connectionInfo.getCpuMajor(),connectionInfo.getCpuMinor(),connectionInfo.getMemoryCritical(),connectionInfo.getMemoryMajor(),connectionInfo.getMemoryMinor(),
							connectionInfo.getHddCritical(),connectionInfo.getHddMajor(),connectionInfo.getHddMinor());
					
					logger.debug(" Collected Information[usedCPU :"+usedCpu+" usedMemrate :"+usedMem+" usedHddrate :"+usedHdd+" totalMem :"+totalMem+" totalHdd :"+totalHdd+"]");
					logger.debug("[Svr Num : "+connectionInfo.getSvrNum()
							+" SerialNo "+connectionInfo.getSerialNo()
							+" Critical Point Range"+" CPU : "+connectionInfo.getCpuCritical()+","+connectionInfo.getCpuMajor()+
							","+connectionInfo.getCpuMinor()+" Memory : "+connectionInfo.getMemoryCritical()+","+connectionInfo.getMemoryMajor()+","+connectionInfo.getMemoryMinor()+" HDD : "+connectionInfo.getHddCritical()+","+connectionInfo.getHddMajor()+
							","+connectionInfo.getHddMinor()+"]");
					
					
					collectInfoList.add(collectInfo);
					break;
				} catch (Exception e) {
					 if (i<3) {
				        	try {
				        		
				        		logger.debug(connectionInfo.getHost()+"'s "+(i+1)+"re-try");	
				        		Thread.sleep(5000);
				        		
							} catch (Exception ee) {
							}  
						
				        }
					}finally {
						if(session!=null) {
							session.disconnect();
						}
					}
			} 
		}
		logger.debug("getReourceList exit");
		return collectInfoList;
		
	}
	
	private String StreamInOut(String Command, Session session) throws SQLException, JSchException, IOException{
		

		ChannelExec channel = (ChannelExec) session.openChannel("exec");
		channel.setCommand(Command);
		channel.setPty(true);
		channel.connect();
		String str = null;
		InputStream in = channel.getInputStream();
		byte[] tmp = new byte[1024];
		
		while(true){
			while (in.available()>0){
				
				 int i = in.read(tmp,0,1024);

				if(i<0)	break;
				str = new String(tmp,0,i); 
			}
			if(channel.isClosed()){
			
				break;
			}
			try{
				Thread.sleep(1000);
			} catch(Exception ee){
			}
			
				channel.disconnect();	
		}
		
		
		return str.replace(System.getProperty("line.separator"), "");
	}
}